import { LikeOutlined, LoadingOutlined, MessageOutlined, StarOutlined } from '@ant-design/icons';
import { Button, Card, Col, Form, List, Row, Select, Tag, DatePicker } from 'antd';
import React, { FC, useState } from 'react';
import { Radio } from 'antd';
import type { RadioChangeEvent } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { Input } from 'antd';
import { useRequest } from 'umi';
import ArticleListContent from './components/ArticleListContent';
import StandardFormRow from './components/StandardFormRow';
import TagSelect from './components/TagSelect';
import type { ListItemDataType } from './data.d';
import { queryNewsList, queryCategoryList, querySourceList } from './service';
import styles from './style.less';
import moment from 'moment';

const { RangePicker } = DatePicker;

const FormItem = Form.Item;

var lastTimeCategory: string[] = [];
var lastTimeSource: string[] = [];
var lastTimeTime: moment.Moment[] = [];
var lastTimeSearch = "";
var lastTimeChoose = "semantic";
const dateFormat = 'YYYY/MM/DD';

const pageSize = 5;

const Articles: FC = () => {
  const search_options = [
    { label: 'Handwritten Boolean', value: 'hand_bool' },
    { label: 'Semantic', value: 'semantic' },
    { label: 'ES-based Boolean', value: 'es_bool' },
  ];
  const [form] = Form.useForm();
  var searchValue = lastTimeChoose;
  var selectedCategory = lastTimeCategory;
  var selectedSource = lastTimeSource;
  var selectedTime = lastTimeTime;
  var search_str = lastTimeSearch;

  console.log(selectedCategory);
  console.log(selectedSource);

  const { data, reload, loading, loadMore, loadingMore } = useRequest(
    (d) => {
      const offSetNum = d? d.list.length : 0;
      var ret;
      if (selectedTime.length > 0){
        const selTime = [selectedTime[0].format(dateFormat), selectedTime[1].format(dateFormat)];
        ret = queryNewsList({
          count: pageSize,
          offSet: offSetNum,
          short: true,
          categories: selectedCategory.join("+"),
          sources: selectedSource.join("+"),
          time: selTime.join("-"),
          type: searchValue,
          query: search_str,
        });
      } else {
        ret = queryNewsList({
          count: pageSize,
          offSet: offSetNum,
          short: true,
          categories: selectedCategory.join("+"),
          sources: selectedSource.join("+"),
          time: "",
          type: searchValue,
          query: search_str,
        });
      }
      return ret;
    },
    {
      loadMore: true,
    },
  );

  const {data: catData} = useRequest(
    () => {
      const ret = queryCategoryList();
      return ret;
    }
  );

  const categoryList = catData?.list ? catData.list : [];

  const {data: sourceData} = useRequest(
    () => {
      const ret = querySourceList();
      return ret;
    }
  );

  const sourceList = sourceData?.list ? sourceData.list : [];
  // console.log(categoryList);
  // console.log(catData);

  // console.log(data)
  var continue_ph = data?.cont;
  var list = data?.list || [];
  // console.log(list);

  const reloadCategory = (d: any) => {
      selectedCategory = d;
      lastTimeCategory = d;
      reload();
    };
  
  const reloadSource = (d:any) => {
    selectedSource = d;
    lastTimeSource = d;
    reload();
  };

  const reloadTime = (d:any) => {
    lastTimeTime = d;
    selectedTime = d;
    reload();
  }

  const reloadSearch = ({ target: { value } }: RadioChangeEvent) => {
    console.log('radio3 checked', value);
    searchValue = value;
    lastTimeChoose = value;
  };

  const loadMoreDom = continue_ph && (
    <div style={{ textAlign: 'center', marginTop: 16 }}>
      <Button onClick={loadMore} style={{ paddingLeft: 48, paddingRight: 48 }}>
        {loadingMore ? (
          <span>
            <LoadingOutlined /> Loading...
          </span>
        ) : (
          'Load More'
        )}
      </Button>
    </div>
  );

  const handleFormSubmit = (value: string) => {
    // eslint-disable-next-line no-console
    console.log(value);
    search_str = value;
    lastTimeSearch = value;
    reload();
  };

  return (
    <>
      <PageContainer
      content={
        <div style={{ textAlign: 'center' }}>
          <Input.Search
            placeholder="Input Query"
            enterButton="Search"
            size="large"
            onSearch={handleFormSubmit}
            defaultValue={search_str}
            style={{ maxWidth: 522, width: '100%' }}
          />
        </div>
      }
    >
      <Card bordered={false}>
        <Form
          layout="inline"
          form={form}
          initialValues={{
            category: selectedCategory,
            source: selectedSource,
          }}
          // onValuesChange={reload}
        >
          <StandardFormRow title="Category Filter" block style={{ paddingBottom: 11 }}>
            <FormItem name="category">
              <TagSelect value={selectedCategory} onChange={reloadCategory} hideCheckAll={true}>
                {
                  categoryList.map((item: string)=> {
                    return <TagSelect.Option value={item} key={item}>{item}</TagSelect.Option>;
                  })
                }
              </TagSelect>
            </FormItem>
          </StandardFormRow>
          <StandardFormRow title="Source Filter" block style={{ paddingBottom: 11 }}>
            <FormItem name="source">
              <TagSelect value={selectedSource} onChange={reloadSource} hideCheckAll={true}>
                {
                  sourceList.map((item: string)=> {
                    return <TagSelect.Option value={item} key={item}>{item}</TagSelect.Option>;
                  })
                }
              </TagSelect>
            </FormItem>
          </StandardFormRow>
          <StandardFormRow title="Date Filter" block style={{ paddingBottom: 11 }}>
            <FormItem name="date">
              <RangePicker format={dateFormat} defaultValue={selectedTime} onChange={reloadTime}/>
            </FormItem>
          </StandardFormRow>
          <StandardFormRow title="Search Filter" block style={{ paddingBottom: 11 }}>
            <FormItem name="type">
            <Radio.Group options={search_options} onChange={reloadSearch} value={searchValue} defaultValue={lastTimeChoose} optionType="button" />
            </FormItem>
          </StandardFormRow>
        </Form>
      </Card>
      <Card
        style={{ marginTop: 24 }}
        bordered={false}
        bodyStyle={{ padding: '8px 32px 32px 32px' }}
      >
        <List<ListItemDataType>
          size="large"
          loading={loading}
          // rowKey="id"
          itemLayout="vertical"
          loadMore={loadMoreDom}
          dataSource={list}
          renderItem={(item) => (
              <ArticleListContent data={item} />
          )}
        />
      </Card>
      </PageContainer>
    </>
  );
};

export default Articles;
